import * as fs from 'fs';
import * as session from 'express-session';
import { NestFactory, PartialGraphHost } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';

import { AppModule } from './app.module';

import { setupSwagger } from '@/core/swagger';
// import { ExceptionsFilter } from '@/filters/exceptions.filter';
import { contentMiddleware } from '@/core/middleware/content.middleware';
import { RequestMethod } from '@nestjs/common';
import { join } from 'path';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    abortOnError: false, // 服务错误时不退出
  });

  // 全局前缀
  app.setGlobalPrefix('diet', {
    exclude: [{ path: '/', method: RequestMethod.GET }],
  });

  app.useStaticAssets(join(__dirname, '../', 'uploads'), {
    prefix: '/static',
  });
  app.use(contentMiddleware);

  app.use(
    session({
      secret: process.env.JWT_SECRET,
      resave: false,
      saveUninitialized: false,
      cookie: { maxAge: 60 * 60 * 1000 }, // 1小时
    }),
  );

  setupSwagger(app);

  const port = process.env.SERVE_PORT;
  const host = process.env.DATABASE_URL;

  await app.listen(port);
  console.log(`🚀 Service: \x1b[34mhttp://${host}:${port}/diet\x1b[0m`);
  console.log(`📄 Swagger JSON: http://${host}:${port}/api-docs`);
}

bootstrap().catch(() => {
  fs.writeFileSync('graph.json', PartialGraphHost.toString() ?? '');
  process.exit(1);
});
